package com.talent.jiwen.my;

import android.annotation.SuppressLint;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.ProgressBar;

import com.afollestad.materialdialogs.MaterialDialog;
import com.talent.jiwen.R;
import com.talent.jiwen.base.BaseActivity;
import com.talent.jiwen.http.common.ApiRetrofit;
import com.talent.jiwen.ui.widgets.SharePopwindow;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * Created by qyqx on 2018/7/20.
 */

public class WebShowActivity extends BaseActivity {

    @BindView(R.id.select_web)
    WebView h5WebView;

    @BindView(R.id.ll_bottom)
    LinearLayout ll_bottom;

    @BindView(R.id.progressBar1)
    ProgressBar progressBar1;

    public static int WEB_SHOW_TYPE = 0;

    public static final int WEB_INVISIT_TYPE = 1;//邀请

    public static final int WEB_CAO_TYPE = 2;//操作手册

    public static final int WEB_XIE_TYPE = 3;//用户协议

    public static final int WEB_CERT_TYPE = 4;//信用规则

    public static int IS_SERVICE_RIGHT=0;//0表示代勾 1 表示不代勾

    public static final int WEB_BOOK_READ = 5;//点读

    public static final int WEB_RECHARGE_PROTOCOL = 6;//充值协议

    public static final int WEB_INVITE_INSTRUCTION = 7;//邀请赚钱说明

    public static final int WEB_CY_GAME = 8;//成语消消乐


    String EDU_URL = ApiRetrofit.EDU_WEB_URL;
    private String webUrl;

    String studentInvisitUrl = EDU_URL + "/customerIndex/studentInviteAndReg?code=" + SPUtil.stringOut(SPConstant.INVITE_CODE) + "&name=" + SPUtil.getUserName();
    String teacherInvisitUrl = EDU_URL + "/customerIndex/teacherInviteAndReg?code=" + SPUtil.stringOut(SPConstant.INVITE_CODE) + "&name=" + SPUtil.getUserName();

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_web_show;
    }

    @Override
    public String titleName() {
        String title = null;
        switch (WEB_SHOW_TYPE) {
            case WEB_INVISIT_TYPE:
                title = "邀请有礼";
                break;
            case WEB_CAO_TYPE:
                title = "操作手册";
                break;
            case WEB_XIE_TYPE:
                title = "用户协议";
                break;
            case WEB_CERT_TYPE:
                title = "信用规则";
                break;
            case WEB_BOOK_READ:
                title = "学吧";
                break;
            case WEB_RECHARGE_PROTOCOL:
                title = "即问充值用户协议";
                break;
            case WEB_INVITE_INSTRUCTION:
                title = "如何邀请赚钱";
                break;
            case WEB_CY_GAME:
                title = "成语消消乐";
                break;
        }

        return title;
    }

    @Override
    protected void initData() {
        switch (WEB_SHOW_TYPE) {
            case WEB_INVISIT_TYPE:
                ll_bottom.setVisibility(View.VISIBLE);
                mHeadRightText.setVisibility(View.VISIBLE);
                mHeadRightText.setText("规则");
                mHeadRightText.setTextColor(getResources().getColor(R.color.text_gray_9));
                webUrl = EDU_URL + "/customerIndex/invitation?id=" + SPUtil.getUserId() + "&type=2";
                break;
            case WEB_CAO_TYPE:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                webUrl = EDU_URL + "/customerIndex/jumpToStudentCaoZuoApp";
                break;
            case WEB_XIE_TYPE:
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                if(IS_SERVICE_RIGHT==0){
                    webUrl=EDU_URL+"/customerIndex/studentAgreement?type=0";
                }else{
                    webUrl=EDU_URL+"/customerIndex/studentAgreement?type=1";
                }
                break;
            case WEB_CERT_TYPE:
                webUrl = EDU_URL + "/customerIndex/commissionRules";
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
//                webUrl=EDU_URL+"/customerIndex/teacherPartTime";
                break;
            case WEB_BOOK_READ:
                setHeadVisibility(View.GONE);
                webUrl = EDU_URL + "/customerIndex/listRead?bookId=" + SPUtil.intOut(SPConstant.SELECT_READ_BOOK_GRADE);
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                break;
            case WEB_RECHARGE_PROTOCOL:
                webUrl = EDU_URL + "/customerIndex/topUpAgreement";
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                break;
            case WEB_INVITE_INSTRUCTION:
                webUrl = EDU_URL + "/customerIndex/jumpToInvitationProcess";
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                break;
            case WEB_CY_GAME:
                setHeadVisibility(View.GONE);
                webUrl = EDU_URL + "/customerIndex/game/idiom/jumpToGameStartPage?Authorization=" + SPUtil.getToken();
                ll_bottom.setVisibility(View.GONE);
                mHeadRightText.setVisibility(View.GONE);
                break;
        }
        initWeb();
    }

    /**
     * LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
     * LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
     * LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
     * LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。
     */
//        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);//不使用缓存，只从网络获取数据.
//
//        //支持屏幕缩放
//        webSettings.setSupportZoom(true);
//        webSettings.setBuiltInZoomControls(true);

    //不显示webview缩放按钮
//        webSettings.setDisplayZoomControls(false);
//
//    }
    @OnClick({R.id.txt_teacher, R.id.txt_student, R.id.text_right})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.txt_teacher:
                showSharePop(teacherInvisitUrl, 1);
                break;
            case R.id.txt_student:
                showSharePop(studentInvisitUrl, 2);
                break;
            case R.id.text_right:
                new MaterialDialog.Builder(this)
                        .title("即问邀请规则")
                        .content(
                                "一、推荐奖励：\n " +
                                        "1.首次交易奖励 15元（注册成功，并且被邀请者产生首次支付的订单，订单上课时间在15分钟以上，直接奖励15元但没有提成，奖励将累计在余额中，可提现，首单奖励无提拥）。\n" +
                                        "2.一线单 1.2元/单，二线单0.5元/单 （每单交易时长必须在15分钟以上）。\n" +
                                        "3.一线单 0.5元/单，二线单0.3元/单 （每单交易时长为5-15分钟，含15分钟，低于5分钟将不能获得提成。\n" +
                                        "备注：\n" +
                                        "（1）一线单：邀请码被直接关联，此被邀请者产生的订单称为一线单; \n" +
                                        "（2）二线单：一线单的被邀请者邀请的被邀请者所产生的订单称之为下线单; \n" +
                                        "（3）所有被邀请者均不能重复，如有重复只算其中一个被邀请关系。 \n" +
                                        "二、股权奖励：\n" +
                                        "您一旦获得股权奖励意味着您将成为本公司的股东，将会获得相关的股权证书和享有相关股东权益，股权奖励条件：\n" +
                                        "1.推荐学生总人数排在公司前5%的介绍人将获得公司股权 （推荐学生数不低于50人，被推荐人每月在“即问”平台上课次数不低于4次，每次不低20分钟，低于此标准者不列入评估范围）。\n" +
                                        "2.第一年的奖励基数为2000股；第二年的奖励基数为1000股；第三年的奖励基数为1000股。\n" +
                                        "三、邀请违规判定标准：\n" +
                                        "1.只有注册，没有交易，判定为无效邀请。 \n" +
                                        "2.课堂进行时自说自话，文不对题，判定为无效交易，并列为刷单行为。 \n" +
                                        "3.学生有投诉情况发生并成立，判定无效交易。\n" +
                                        "4.无效交易将不能参与以上的奖励条款。"

                        )
                        .positiveText("确定")
                        .showListener(new DialogInterface.OnShowListener() {
                            @Override
                            public void onShow(DialogInterface dialog) {
                            }
                        })
                        .cancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                            }
                        })
                        .dismissListener(new DialogInterface.OnDismissListener() {
                            @Override
                            public void onDismiss(DialogInterface dialog) {
                            }
                        }).show();
                break;
        }
    }


    private void showSharePop(String url, int type) {
        SharePopwindow pop = new SharePopwindow(WebShowActivity.this, 0, url, SPUtil.getUserName(), type);
        pop.showAtLocation(WebShowActivity.this.findViewById(R.id.view),
                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
    }

    // 初始化webview
    @SuppressLint("SetJavaScriptEnabled")
    private void initWeb() {


        WebSettings mWebSettings = h5WebView.getSettings();
        mWebSettings.setJavaScriptEnabled(true); //允许加载javaScript
        mWebSettings.setSupportZoom(true);       //是否允许缩放
        mWebSettings.setUseWideViewPort(true);   //设置加载进来的页面自适应手机屏幕
        mWebSettings.setLoadWithOverviewMode(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        mWebSettings.setRenderPriority(WebSettings.RenderPriority.HIGH);


        h5WebView.setWebViewClient(new WebViewClient() {
            //覆写shouldOverrideUrlLoading实现内部显示网页
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // TODO 自动生成的方法存根
                if (url != null && url.contains("/html/html")) {
                    Intent intent = new Intent();
                    setResult(1001, intent);
                    finish();
                }else if(url != null && url.contains("/returnBooksList.html")){
                    finish();
                }else if (url != null && url.contains("/returnIdiom.html")){
                    finish();
                }else{
                    view.loadUrl(url);
                }
                return true;
            }
        });


        h5WebView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根

                if (newProgress == 100) {
                    progressBar1.setVisibility(View.GONE);//加载完网页进度条消失
                } else {
                    progressBar1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar1.setProgress(newProgress);//设置进度值
                }
            }
        });

        h5WebView.canGoBack();
        h5WebView.loadUrl(webUrl);


        //H5界面加载进度监听
//        h5WebView.setWebChromeClient(new WebChromeClient(){
//            @Override
//            public void onProgressChanged(WebView view, int newProgress) {
//
////                if (webProgressBar != null){
////                    if (newProgress > 95){
////                        webProgressBar.setVisibility(View.GONE);
////                    }else if (newProgress < 95 && webProgressBar.getVisibility() == View.GONE){
////                        webProgressBar.setVisibility(View.VISIBLE);
////                    }
////                    webProgressBar.setProgress(newProgress);
////                }
//                super.onProgressChanged(view, newProgress);
//            }
//
//        });

        /**
         * 监听手机返回按键，点击返回H5就返回上一级
         */
        h5WebView.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && h5WebView.canGoBack()) {
                    if (WEB_SHOW_TYPE == WEB_CY_GAME){
                        return false;
                    }else{
                        h5WebView.goBack();
                        return true;
                    }
                }

                return false;
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (WEB_SHOW_TYPE != WEB_CY_GAME){
            super.onBackPressed();
        }else{
            if (!h5WebView.canGoBack()){
                super.onBackPressed();
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        //释放资源
        h5WebView.destroy();
        h5WebView = null;
    }

}
